import scrapy
import requests,json
from bid.items import BidItem
from bid.tools import *


class ChongqingSpider(scrapy.Spider):
    name = 'chongqing'
    allowed_domains = ['ggzyjyjgj.cq.gov.cn']
    start_urls = ['http://ggzyjyjgj.cq.gov.cn']
    url = 'http://ggzyjyjgj.cq.gov.cn/EpointWebBuilder/SearchAction.action?cmd=getPageInfoListNew'
    t_dic ={
        '002001001':['工程招投标-招标公告','1'],
        '002001005':['工程招投标-中标候选人公示','2'],
        '002001003':['工程招投标-中标结果公告','3'],
        '002001006':['工程招投标-相关公告公示','2'],
        '002002001':['政府采购-采购公告','1'],
        '002002002':['政府采购-答疑变更','2'],
        '002002003':['政府采购-采购结果公告','3'],
        '002005001':['中介超市-通知公告','2'],
        '002005002':['中介超市-采购公告','1'],
        '002005003':['中介超市-中选公告','3'],
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg =[]
    def start_requests(self):
        for page in range(1,999999):
            data = {
            'title': '',
            'pageSize': '20',
            'pageIndex': str(page),
            'siteguid': '7eb5f7f1-9041-43ad-8e13-8fcb82ea831a',
            'categorynum': '002',
            }
            res = requests.post(url=self.url,data=data,headers=self.headers).json()
            ls = json.loads(res['custom'])['infodata']
            last_page = json.loads(res['custom'])['TotalCount']//20+1
            if page > last_page:
                break
            for l in ls:
                item = {}
                item['link'] = 'http://ggzyjyjgj.cq.gov.cn' + l['infourl']
                key = item['link'].split('/')[-3]
                if key not in self.t_dic:
                    continue
                item['title'] = l['title']
                item['time'] = l['infodate']
                item['classification'] = '重庆-'+self.t_dic[key][0]
                item['typ']=self.t_dic[key][-1]
                if redis_dupefilter(item) or item['time'].startswith('2021'):
                    self.msg.append(page)
                    break
                yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
            if page in self.msg:
                print('完成')
                break
            time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="ewb-article-info news_content"]')
        item = get_field(dict(item))
        yield item